<template>
  <!-- 搜索 + 列设置 -->
  <a-space align="center" style="width:100%; justify-content:center; margin-bottom:16px;">
    <a-form :model="formSearchParams" layout="inline" @submit="doSearch">
      <a-form-item field="appName" label="测评名称">
        <a-input
          v-model="formSearchParams.appName"
          placeholder="请输入测评活动名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="appDesc" label="测评描述">
        <a-input
          v-model="formSearchParams.appDesc"
          placeholder="请输入测评活动描述"
          allow-clear
        />
      </a-form-item>
      <div class="form-break"></div>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-popover trigger="click" title="选择要展示的列">
            <template #content>
              <a-checkbox-group
                v-model="selectedKeys"
                :options="columnOptions"
              />
            </template>
            <a-button>列设置</a-button>
          </a-popover>
        </a-space>
      </a-form-item>
    </a-form>
  </a-space>

  <!-- 列表 -->
  <a-table
    :columns="visibleColumns"
    :data="dataList"
    :pagination="{
      showTotal: true,
      pageSize: searchParams.pageSize,
      current: searchParams.current,
      total
    }"
    @page-change="onPageChange"
  >
    <template #appIcon="{ record }">
      <a-image width="64" :src="record.appIcon" />
    </template>
    <template #appType="{ record }">
      {{ APP_TYPE_MAP[record.appType] }}
    </template>
    <template #scoringStrategy="{ record }">
      {{ APP_SCORING_STRATEGY_MAP[record.scoringStrategy] }}
    </template>
    <template #reviewStatus="{ record }">
      {{ REVIEW_STATUS_MAP[record.reviewStatus] }}
    </template>
    <template #reviewTime="{ record }">
      {{
        record.reviewTime &&
        dayjs(record.reviewTime).format("YYYY-MM-DD HH:mm:ss")
      }}
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button status="danger" @click="doDelete(record)">删除</a-button>
      </a-space>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { ref, watchEffect, computed } from "vue";
import API from "@/api";
import {
  listMyAppVoByPageUsingPost,
  deleteAppUsingPost1,
} from "@/api/appController";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import type { CheckboxOption } from "@arco-design/web-vue";
import {
  APP_SCORING_STRATEGY_MAP,
  APP_TYPE_MAP,
  REVIEW_STATUS_MAP,
} from "@/constant/app";

// 1. 定义所有可选列
interface ColDef {
  key: string;
  title: string;
  dataIndex?: string;
  slotName?: string;
}
const allColumns: ColDef[] = [
  { key: "id",             title: "ID",               dataIndex: "id" },
  { key: "appName",        title: "名称",             dataIndex: "appName" },
  { key: "appDesc",        title: "描述",             dataIndex: "appDesc" },
  { key: "appIcon",        title: "图标",             dataIndex: "appIcon",        slotName: "appIcon" },
  { key: "appType",        title: "类型",             dataIndex: "appType",        slotName: "appType" },
  { key: "scoringStrategy",title: "评分策略",         dataIndex: "scoringStrategy",slotName: "scoringStrategy" },
  { key: "reviewStatus",   title: "审核状态",         dataIndex: "reviewStatus",   slotName: "reviewStatus" },
  { key: "reviewMessage",  title: "审核信息",         dataIndex: "reviewMessage" },
  { key: "reviewTime",     title: "审核时间",         dataIndex: "reviewTime",     slotName: "reviewTime" },
  { key: "reviewerId",     title: "审核人 ID",        dataIndex: "reviewerId" },
  { key: "createTime",     title: "创建时间",         dataIndex: "createTime",     slotName: "createTime" },
  { key: "updateTime",     title: "更新时间",         dataIndex: "updateTime",     slotName: "updateTime" },
  { key: "optional",       title: "操作",             slotName: "optional" },
];

// 2. 默认展示列
const defaultKeys = [
  "appName",
  "appDesc",
  "appIcon",
  "appType",
  "createTime",
  "optional",
];
const selectedKeys = ref<string[]>([...defaultKeys]);

// 3. 复选框选项
const columnOptions = computed<CheckboxOption[]>(() =>
  allColumns.map((col) => ({ label: col.title, value: col.key }))
);

// 4. 计算实际可见列
const visibleColumns = computed(() =>
  allColumns
    .filter((col) => selectedKeys.value.includes(col.key))
    .map((col) => {
      const c: any = { title: col.title, key: col.key };
      if (col.dataIndex) c.dataIndex = col.dataIndex;
      if (col.slotName) c.slotName = col.slotName;
      return c;
    })
);

// 搜索 & 分页状态
const formSearchParams = ref<Partial<API.AppQueryRequest>>({});
const initSearchParams = { current: 1, pageSize: 10 };
const searchParams = ref<Partial<API.AppQueryRequest>>({ ...initSearchParams });
const dataList = ref<API.AppVO[]>([]);
const total = ref(0);

// 拉取“我创建的测评”
async function loadData() {
  const res = await listMyAppVoByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败：" + res.data.message);
  }
}

// 搜索
function doSearch() {
  searchParams.value = { ...initSearchParams, ...formSearchParams.value };
}

// 分页
function onPageChange(page: number) {
  searchParams.value = { ...searchParams.value, current: page };
}

// 删除
async function doDelete(record: API.AppVO) {
  if (!record.id) return;
  const res = await deleteAppUsingPost1({ id: record.id });
  if (res.data.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败：" + res.data.message);
  }
}

watchEffect(loadData);
</script>
<style scoped>
.form-break {
  flex-basis: 100%;
  height: 0;
  margin: 0;
  padding: 0;
}
</style>
